package com.bk.interceptor;

import com.bk.controller.BKController;
import com.cjw.model.DBMap;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.moomi.common.model.BkShop;
import com.moomi.common.model.BkUser;
import com.moomi.common.model.BkUserShop;
import com.utils.AuthUtils;

import cn.hutool.core.util.NumberUtil;

public class BKInterceptor extends CJWInterceptor {

	@Override
	public void generateSlider(Controller controller) {

		try {
			String uid = AuthUtils.getTokenUid(controller);
			if (!NumberUtil.isInteger(uid)) {
				return;
			}
			BkUser user = BkUser.dao.findById(Integer.parseInt(uid));
			if (user.getIsVIP() != null) {
				addSlider("分店管理", "branchOffice");
			}
		} catch (Exception e) {
			LogKit.error("获取会员状态失败");
		}
		addSlider("服务管理", "item");
		addSlider("技师管理", "selection");
		addSlider("预约管理", "booking");
		addSlider("店铺管理", "shop");
		addSlider("登出", "user/logout");
	}

	@Override
	public void intercept(Invocation invocation) {
		Controller controller = invocation.getController();
		try {
			BKController bkController = (BKController) controller;
			String ip = IpKit.getRealIpV2(invocation.getController().getRequest());
			// LogKit.info(ip);
			// LogKit.info(AuthUtils.getTokenUid(controller));
			if (!AuthUtils.verify(controller)) {
				bkController.renderFailure(401, "登录失败");
				return;
			}
			super.intercept(invocation);
		} catch (Exception e) {
			LogKit.error("system error", e);
			controller.renderError(404);
		}
	}

	@Override
	public void setupAttribute(Controller controller) {
		super.setupAttribute(controller);
		BKController bkController = (BKController) controller;
		controller.setAttr("systemTitle", "蓁预订");
		controller.setAttr("subtitle", "");
		Integer shopId = bkController.getShopId();
		if (shopId == null) {
			String uid = AuthUtils.getTokenUid(controller);
			if (uid != null) {
				if (!NumberUtil.isInteger(uid)) {
					return;
				}
				LogKit.info("uid: " + uid);
				BkUser user = BkUser.dao.findById(Integer.parseInt(uid));
				DBMap map = new DBMap();
				map.put("userId", user.getId());
				BkUserShop userShop = BkUserShop.dao.searchFirst(map);
				shopId = userShop.getShopId();
			}
		}
		controller.setAttr("systemSubtitle", "");
		if (shopId != null) {
			try {
				BkShop shop = BkShop.dao.findById(shopId);
				if (shop != null) {
					String shopName = shop.getName();
					controller.setAttr("systemSubtitle", shopName);
				}
				controller.setAttr("shopId", shopId);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public String key() {
		return "bk";
	}

}
